<?
include("inc_security.php");

//Khai báo biến khi thêm mới
$after_save_data	= getValue("after_save_data", "str", "POST", "bando.php");
$gs_title			= "Bản đồ";
$gs_action			= getURL();
$gs_redirect		= $after_save_data;
$gs_errorMsg		= "";

//Get action variable for add new data
$action				= getValue("action", "str", "POST", "");

//Check $action for insert new data
if($action == "insert"){
	
	$gmap_address = getValue('gmap_address', 'str', 'POST', '');
	$gmap_phone = getValue('gmap_phone', 'str', 'POST', '');
	$gmap_order = getValue('gmap_order', 'dbl', 'POST', '');
	$gmap_default = getValue('gmap_default', 'int', 'POST', '');
	
	
	$gmap_lng = getValue('lng', 'dbl', 'POST', 0);
	$gmap_lat = getValue('lat', 'dbl', 'POST', 0);
	
	//Lấy dữ liệu kiểu checkbox
	$gmap_default		= getValue("gmap_default", "int", "POST", 0);
	
	/*
	Call class form:
	1). Ten truong
	2). Ten form
	3). Kieu du lieu , 0 : string , 1 : kieu int, 2 : kieu email, 3 : kieu double, 4 : kieu hash password
	4). Noi luu giu data  0 : post, 1 : variable
	5). Gia tri mac dinh, neu require thi phai lon hon hoac bang default
	6). Du lieu nay co can thiet hay khong
	7). Loi dua ra man hinh
	8). Chi co duy nhat trong database
	9). Loi dua ra man hinh neu co duplicate
	*/
	$myform = new generate_form();
	//Add table insert data
	$myform->addTable('google_maps');
	$myform->add("gmap_address", "gmap_address", 0, 1, " ", 1, "Bạn chưa nhập Địa chỉ.", 0, "");
	$myform->add('gmap_lng','gmap_lng',3,1,' ',0,'',0,'');
	$myform->add('gmap_lat','gmap_lat',3,1,' ',0,'',0,'');
	$myform->add('gmap_phone','gmap_phone',0,1,' ',0,'',0,'');
    $myform->add('gmap_order','gmap_order',3,1,' ',0,'',0,'');
	$myform->add('gmap_default','gmap_default',1,1,0,0,'',0,'');
	
	//Check form data
	$gs_errorMsg .= $myform->checkdata();
	
	if($gs_errorMsg == ""){
		
		//Insert to database
		$myform->removeHTML(0);
		$db_insert	= new db_execute_return();
		$last_id		= $db_insert->db_execute($myform->generate_insert_SQL());
		unset($db_insert);
		
		if($last_id > 0){
			
			//Redirect after insert complate
			redirect($gs_redirect);
			
		}
		else{
			$gs_errorMsg .= "&bull; Không insert được vào database. Bạn hãy kiểm tra lại câu lệnh INSERT INTO.<br />";
		}
		
	}//End if($gs_errorMsg == "")
	unset($myform);
	
}//End if($action == "insert")

//Check $action for update data
if($action == "update"){
	
	//Get data edit
	$record_id			= getValue("record_id");
	$record_id			= getValue("record_id", "int", "POST", $record_id);
	$db_edit				= new db_query("SELECT * FROM google_maps WHERE gmap_id = " . $record_id . " AND lang_id = " . $lang_id);
	if(mysql_num_rows($db_edit->result) == 0){
		//Redirect if can not find data
		redirect($gs_error);
	}
	$edit					= mysql_fetch_array($db_edit->result);
	unset($db_edit);
	
	$gmap_address = getValue('gmap_address', 'str', 'POST', $edit['gmap_address']);
	$gmap_phone = getValue('gmap_phone', 'str', 'POST', $edit['gmap_phone']);
	$gmap_order = getValue('gmap_order', 'dbl', 'POST', $edit['gmap_order']);
	$gmap_default = getValue('gmap_default', 'int', 'POST', $edit['gmap_default']);
	
	//Lấy dữ liệu kiểu checkbox
	$gmap_default		= getValue("gmap_default", "int", "POST", 0);
	
	/*
	Call class form:
	1). Ten truong
	2). Ten form
	3). Kieu du lieu , 0 : string , 1 : kieu int, 2 : kieu email, 3 : kieu double, 4 : kieu hash password
	4). Noi luu giu data  0 : post, 1 : variable
	5). Gia tri mac dinh, neu require thi phai lon hon hoac bang default
	6). Du lieu nay co can thiet hay khong
	7). Loi dua ra man hinh
	8). Chi co duy nhat trong database
	9). Loi dua ra man hinh neu co duplicate
	*/
	$myform = new generate_form();
	//Add table insert data
	$myform->addTable('google_maps');
	$myform->add("gmap_address", "gmap_address", 0, 1, " ", 1, "Bạn chưa nhập Địa chỉ.", 0, "");
	$myform->add('gmap_phone','gmap_phone',0,1,' ',0,'',0,'');
    $myform->add('gmap_order','gmap_order',3,1,' ',0,'',0,'');
	$myform->add('gmap_default','gmap_default',1,1,0,0,'',0,'');
	
	//Check form data
	$gs_errorMsg .= $myform->checkdata();
	
	if($gs_errorMsg == ""){
		//Insert to database
		$myform->removeHTML(0);
		$db_update = new db_execute($myform->generate_update_SQL('gmap_id', $record_id));
		unset($db_update);
		
		//Redirect after insert complate
		redirect($gs_redirect);
		
	}//End if($gs_errorMsg == "")
	unset($myform);
	
}//End if($action == "insert")

$numCity = 2;
$arrCity = array(0 => array('city_id' => 1, 'city_name' => 'Hà Nội', 'city_lat' => 21.027521, 'city_lng' => 105.852449),
				1 => array('city_id' => 2, 'city_name' => 'Hồ Chí Minh', 'city_lat' => 10.759579, 'city_lng' => 106.668661),
				);

$sqlWhere = "";
$sqlOrderBy = "gmap_order ASC";
//End get page break params
$db_listing	= new db_query("SELECT *
									 FROM google_maps
									 WHERE lang_id = " . $lang_id . $sqlWhere . "
									 ORDER BY " . $sqlOrderBy);
$No = 0;
$arrListing = array();
while ($listing = mysql_fetch_array($db_listing->result))
{
	$arrListing[$No] = $listing;
	++$No;
}

// lay dia diem mac dinh
if ($No > 0)
{
	$default_lat = $arrListing[0]['gmap_lat'];
	$default_lng = $arrListing[0]['gmap_lng'];
}
else
{
	$default_lat = $arrCity[0]['city_lat'];
	$default_lng = $arrCity[0]['city_lng'];
}
?>
<html>
<head>
<title>Bản đồ</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css" media="all">@import "../css/GSportal.css";</style>
<style type="text/css">
.left_menu{
	background:url(../images/arrow.gif) no-repeat 0px 3px;
	font-size:12px;
	color:#e86402;
	padding-left:13px;
	text-decoration:none;
}
.left_menu:hover{
	text-decoration:underline;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script language="javascript" type="text/javascript">
	var map;	
	var clickmarker;		
	var infowindow;
	var marker_placed = false;
	var marker = new Array();
	var old_id = 0;
	var infoWindowArray = new Array();
	var infowindow_array = new Array();
	var city_location = new Array();
	
	function initialize() {
		var defaultLatLng = new google.maps.LatLng(<?=$default_lat?>,<?=$default_lng?>); 
		var myOptions = { zoom: 16, 
							  center: defaultLatLng, 
							  scrollwheel : false,
							  mapTypeId: google.maps.MapTypeId.ROADMAP }; 
							  
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		
		map.setCenter(defaultLatLng);
		<? for ($i=0;$i<$No;$i++) {?>
			var arrLatLng = new google.maps.LatLng(<?=$arrListing[$i]['gmap_lat']?>,<?=$arrListing[$i]['gmap_lng']?>);
			infoWindowArray[<?=$arrListing[$i]['gmap_id']?>] = '<form method="post"><table width="350"><tr><td colspan="2" class="content_title">Sửa / Xóa địa chỉ</td></tr><tr><td nowrap="nowrap" class="form_name"><font color="red">*</font>Địa chỉ:</td><td><input type="text" name="gmap_address" id="gmap_address_<?=$arrListing[$i]['gmap_id']?>" class="form_control" style="width:230px" maxlength="200" value="<?=$arrListing[$i]['gmap_address']?>" /></td></tr><tr><td class="form_name">Điện thoại:</td><td><input type="text" name="gmap_phone" class="form_control" style="width:230px" maxlength="200" value="<?=$arrListing[$i]['gmap_phone']?>"/></td></tr><tr><td class="form_name">Thứ tự:</td><td><input type="text" name="gmap_order" class="form_control" style="width:50px" maxlength="5" value="<?=$arrListing[$i]['gmap_order']?>"/></td></tr><tr><td class="form_name">Trụ sở chính:</td><td><input type="checkbox" name="gmap_default" value="1" class="form_control"<? if ($arrListing[$i]['gmap_default']) { echo ' checked="checked"';}?> /></td></tr><tr><td colspan="2" align="center"><input type="submit" value="Sửa chữa" class="form_button" onclick="return checkForm(<?=$arrListing[$i]['gmap_id']?>)"/>&nbsp;&nbsp;&nbsp;<input type="button" value="Xóa" onclick="if (confirm(\'Bạn có chắc muốn xóa địa chỉ này không?\')) { window.location.href=\'xoabando.php?record_id=<?=$arrListing[$i]['gmap_id']?>&authen_code=<?=md5($arrListing[$i]['gmap_id'])?>\'; }" class="form_button"/></td></tr></table><input type="hidden" name="action" value="update" /><input type="hidden" name="record_id" value="<?=$arrListing[$i]['gmap_id']?>" /></form>';
			
			loadMarker(arrLatLng, infoWindowArray[<?=$arrListing[$i]['gmap_id']?>], <?=$arrListing[$i]['gmap_id']?>);
			<? }?>
				google.maps.event.addListener(map, 'click', function(event) { 
			//Nếu đã đặt icon rồi thì phải cancel   
			if(marker_placed){
				Cancel();
			}
			placeMarker(event.latLng);
			marker_placed = true;
    	});
		
		<?
		for ($i=0;$i<$numCity;$i++)
		{
		?>
		city_location[<?=$arrCity[$i]['city_id']?>] = new google.maps.LatLng(<?=$arrCity[$i]['city_lat']?>, <?=$arrCity[$i]['city_lng']?>);
		<?
		}
		?>
				
	}
	
	function placeMarker(location) {
		var clickedLocation = new google.maps.LatLng(location);
		clickmarker = new google.maps.Marker({
			position: location,
			clickable: false,
			map: map
		});
		//map.setCenter(location);
		
				
		var contentString = '<form method="post"><table width="350"><tr><td colspan="2" class="content_title">Nhập mới địa chỉ</td></tr><tr><td nowrap="nowrap" class="form_name"><font color="red">*</font>Địa chỉ:</td><td><input type="text" name="gmap_address" id="gmap_address_0" class="form_control" style="width:230px" maxlength="200" /></td></tr><tr><td class="form_name">Điện thoại:</td><td><input type="text" name="gmap_phone" class="form_control" style="width:230px" maxlength="200" /></td></tr><tr><td class="form_name">Thứ tự:</td><td><input type="text" name="gmap_order" class="form_control" style="width:50px" maxlength="5" /></td></tr><tr><td class="form_name">Trụ sở chính:</td><td><input type="checkbox" name="gmap_default" class="form_control" value="1" /></td></tr><tr><td colspan="2" align="center"><input type="submit" value="Lưu lại" class="form_button" onclick="return checkForm(0)" />&nbsp;&nbsp;&nbsp;<input type="button" value="Hủy bỏ" onclick="Cancel();" class="form_button"/></td></tr></table><input type="hidden" name="lat" value="' + location.lat() + '" /><input type="hidden" name="lng" value="' + location.lng() + '" /><input type="hidden" name="action" value="insert" /></form>';

		infowindow = new google.maps.InfoWindow({content: contentString});
		infowindow.open(map,clickmarker);
		
		google.maps.event.addListener(infowindow, 'closeclick', function() { clickmarker.setVisible(false); clickable=true;});
	}
	
	function Cancel(){
		clickmarker.setVisible(false); 
		infowindow.close();
		marker_placed = false;
	}
	
	function loadMarker(myLocation, myInfoWindow, id) {
		marker[id] = new google.maps.Marker({
			position: myLocation, 
			map: map,
			visible:true
		});
		
		var popup = myInfoWindow; 
		
		infowindow_array[id] = new google.maps.InfoWindow( { content: popup});
		
		google.maps.event.addListener(marker[id], 'click', function() {
			infowindow_array[id].open(map, marker[id]);
		});
	}
	
	//Di chuyển đến địa chỉ click
	function moveToMaker(id){
		//Thiết lập vị trí center
		var location = marker[id].position;
		map.setCenter(location);
		
		//Close old info
		if (old_id > 0) infowindow_array[old_id].close();
		//Show info
		infowindow_array[id].open(map, marker[id]);
		//Gán old_id vào để sau còn close infowindow
		old_id = id;
	}
	
	function changeCityMap(){
		map.setCenter(city_location[document.getElementById("city_map").value]);
	}
	
	function checkForm(id){
		if (document.getElementById("gmap_address_" + id).value == ""){
			alert('Bạn hãy nhập vào địa chỉ');
			document.getElementById("gmap_address_" + id).focus();
			return false;
		}
		return true;
	}
	
	//Đổi độ rộng bản đồ
	function change_map_size(value){
		switch (value){
			case "1": 
				document.getElementById("map_canvas").style.width = "600px"; 
				document.getElementById("map_canvas").style.height = "400px"; 
			break;
			case "2": 
				document.getElementById("map_canvas").style.width = "800px"; 
				document.getElementById("map_canvas").style.height = "500px"; 
			break;
			case "3": 
				document.getElementById("map_canvas").style.width = "1024px"; 
				document.getElementById("map_canvas").style.height = "600px"; 
			break;
		}
	}
</script>
</head>
<body onLoad="initialize()">
<div class="bg_title_content">
<div class="content_title" style="float:left">Bản đồ</div>
</div>

<div align="center" class="content">
		<table width="100%">
		<tr>
			<td colspan="2" class="form_text" align="center">
				<b>Hướng dẫn:</b> Bạn hãy chọn thành phố nơi công ty, cửa hàng bạn đặt trụ sở, sau đó bạn tìm chính xác vị trí trên bản đồ rồi Click vào vị trí đó để điền <b>địa chỉ</b>, <b>số điện thoại</b> và thứ tự hiển thị.<br>

				Bạn có thể nhập nhiều địa chỉ nếu công ty, cửa hàng của bạn có nhiều chi nhánh, văn phòng.
			</td>
		</tr>
		<tr bgcolor="#F2F2F2">
			<td colspan="2" class="form_text" align="center">
				Chọn thành phố:
				<select id="city_map" class="form_control">
                <?
                for ($i=0;$i<$numCity;$i++)
				{
				?>
                <option value="<?=$arrCity[$i]['city_id']?>">Bản đồ <?=$arrCity[$i]['city_name']?></option>
                <?
				}
				?>
				</select>

				<input type="button" class="form_button" value=" Chuyển bản đồ " onClick="changeCityMap()">
				&nbsp;&nbsp; Độ rộng bản đồ:
				<select class="form_control" onChange="change_map_size(this.value)">
					<option value="1">600x400</option>
					<option value="2">800x500</option>
					<option value="3">1024x600</option>
				</select>

			</td>
		</tr>
		<tr>
			<td valign="top">
            <?
            for ($i=0;$i<$No;$i++)
			{
			?>
            	<div style="padding-bottom:10px"><span class="left_menu" style="cursor:pointer" onClick="moveToMaker(<?=$arrListing[$i]['gmap_id']?>)"><?=$arrListing[$i]['gmap_address']?></span><? if ($arrListing[$i]['gmap_default']) {?> <span class="form_text">(Trụ sở chính)</span><? }?><br><span class="form_text">Phone: <?=$arrListing[$i]['gmap_phone']?></span><br><img hspace="5" align="abs_middle" src="/images/edit.gif" style="cursor:pointer" onClick="moveToMaker(<?=$arrListing[$i]['gmap_id']?>)" title="Sửa chữa địa chỉ"><img hspace="5" align="abs_middle" src="/images/delete.gif" style="cursor:pointer" onClick="if (confirm('Bạn có chắc muốn xóa địa chỉ này không?')) { window.location.href='xoabando.php?record_id=<?=$arrListing[$i]['gmap_id']?>&authen_code=<?=md5($arrListing[$i]['gmap_id'])?>'; }" title="Xóa địa chỉ"></div>
            <?
			}
			?>
			</td>
			<td valign="top"><div id="map_canvas" style="width:600px; height:400px"></div></td>
		</tr>
	</table>
</div>
</body>
</html>